package com.wechar_rpa.config;

import com.wechatpay.java.service.payment.WeChatPayService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;

@Configuration
public class WeChatPayConfig {

    @Value("${wechatpay.mch-id}")
    private String mchId;

    @Value("${wechatpay.mch-serial-no}")
    private String mchSerialNo;

    @Value("${wechatpay.private-key-path}")
    private String privateKeyPath;

    @Value("${wechatpay.api-v3-key}")
    private String apiV3Key;

    @Bean
    public WeChatPayService weChatPayService() throws FileNotFoundException {
        // 加载商户私钥（.pem格式）
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new FileInputStream(privateKeyPath));

        return new WeChatPayService.Builder()
                .config(
                        new WeChatPayV3Config(
                                mchId,
                                mchSerialNo,
                                merchantPrivateKey,
                                apiV3Key
                        )
                ).build();
    }

    static class WeChatPayV3Config implements WeChatPayService.Config {
        private final String mchId;
        private final String mchSerialNo;
        private final PrivateKey merchantPrivateKey;
        private final String apiV3Key;

        public WeChatPayV3Config(String mchId, String mchSerialNo, PrivateKey merchantPrivateKey, String apiV3Key) {
            this.mchId = mchId;
            this.mchSerialNo = mchSerialNo;
            this.merchantPrivateKey = merchantPrivateKey;
            this.apiV3Key = apiV3Key;
        }

        @Override
        public String getMchId() {
            return mchId;
        }

        @Override
        public String getMchSerialNo() {
            return mchSerialNo;
        }

        @Override
        public PrivateKey getMerchantPrivateKey() {
            return merchantPrivateKey;
        }

        @Override
        public String getApiV3Key() {
            return apiV3Key;
        }

        @Override
        public X509Certificate getWechatPayCertificate() {
            // 可选：加载微信平台证书，用于验签
            return null;
        }
    }
}